package org.spbsu.apco.server.authorization;

import javax.ws.rs.core.HttpHeaders;
import org.spbsu.apco.common.AuthorizationService;
import org.spbsu.apco.common.utils.NetworkUtils;
import org.spbsu.apco.server.system.Runner;
import org.spbsu.apco.server.system.SystemManager;

import javax.annotation.Resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.atomic.AtomicLong;

/**
 * User: solozobov
 * Date: 12.01.13
 */

@Path("/authorization")
public class AuthorizationServiceImpl implements AuthorizationService {
    private AtomicLong nextClientId = new AtomicLong(0);

    @Resource(name = "SystemService")
    private SystemManager systemManager;
    
    @Override
    @GET
    @Path("/getid")
    @Produces({MediaType.TEXT_PLAIN})
    public String getId(@QueryParam("threads-count") final int threadsCount, @Context HttpHeaders headers) {
        final String clientId = nextClientId.getAndIncrement() + "";
        final Runner runner = systemManager.registerRunner(clientId);
        if (headers != null) {
            runner.setMacAddress(String.valueOf(headers.getRequestHeader(NetworkUtils.X_MAC_SRC)));
        }
        runner.setThreadsCount(threadsCount);
        return clientId;
    }
}
